package controllers.web;

import java.util.Map;

import models.Target;

import org.codehaus.jackson.node.ObjectNode;

import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
import views.html.result;
import controllers.data.RequestController;


public class Application extends Controller
{

    public static Result index()
    {
        Map<String, String[]> req = request().queryString();
        if(req.containsKey("query")) {
            System.out.println(req.get("query")[0].trim());
        }
        System.out.println(request().toString());
        return ok(index.render("LODE Villain"));
    }


    public static Result getInformation()
    {
        Map<String, String[]> req = request().queryString();
        String source = req.get("source")[0].trim();
        String query = req.get("query")[0].trim();

        ObjectNode result = Json.newObject();
        result.put("source", source);
        result.put("query", query);
        result.put("request", "query: " + query + " source: " + source);

        Target t = Target.valueOf(source);
        if(t != null) {
            result.put("content", RequestController.getData(query, t));
        } else {
            result.put("content", "the resource " + source + " doesn't exist.");
        }
        return ok(result);
    }


    public static Result show()
    {
        Map<String, String[]> req = request().queryString();
        String source = req.get("source")[0].trim();
        String id = req.get("id")[0].trim();
        String uri = RequestController.urlMap.get(id);

        Target t = Target.valueOf(source);
        if(t != null) {
            return ok(result.render(uri, t, id));
        } else {
            return ok("content", "the resource " + source + " doesn't exist.");
        }
    }

    public static Result loadInstance()
    {
        Map<String, String[]> req = request().queryString();
        String id = req.get("id")[0].trim();
        String sourceString = req.get("source")[0].trim();
        Target sourceTarget = Target.valueOf(sourceString);

        return ok(RequestController.loadInstance(id,sourceTarget));
    }

    public static Result ai()
    {
        Map<String, String[]> req = request().queryString();

        String id = req.get("id")[0].trim();
        String url = RequestController.urlMap.get(id);

        String sourceString = req.get("source")[0].trim();
        String targetString = req.get("target")[0].trim();

        Target sourceTarget = Target.valueOf(sourceString);
        Target targetTarget = Target.valueOf(targetString);
        if(url == null || sourceTarget == null || targetTarget == null) {
            return ok("an error occured");
        } else {
            return ok(RequestController.startAI(id, sourceTarget, targetTarget));
        }
    }

}